package com.bsy.framework.base

import android.app.Activity
import android.app.Application
import android.content.ComponentCallbacks
import android.content.res.Configuration
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.ViewModelStore
import com.bsy.framework.log.LogUtil
import com.bsy.framework.manager.ActivityManager
import com.bsy.framework.manager.AppFrontBack
import com.bsy.framework.manager.AppFrontBackListener
import com.bsy.framework.task.APPHelperTask
import com.bsy.framework.task.AppManagerTask
import com.bsy.framework.task.MMKVTask
import com.bsy.framework.task.RefreshLayoutTask
import com.bsy.framework.toast.Toaster
import com.bsy.stater.dispatcher.TaskDispatcher
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.ScreenUtils

/**
 * Created by Sincerity on 2024/3/5.
 * Copyright
 * 描述：
 */
abstract class BaseApplication : Application() {
    private var mHandler = Handler(Looper.getMainLooper())

    private var mCurrentActivity: Activity? = null

    private var mAutoSizeRunnable: Runnable? = null

    private var dispatcher: TaskDispatcher? = null
    override fun onCreate() {
        super.onCreate()
        //注册APP前后台切换监听
        appFrontBackRegister()
        // App启动立即注册监听
        Toaster.init(this)
        //1.启动器：TaskDispatcher初始化
        TaskDispatcher.init(this)
        //2.创建dispatcher实例
        dispatcher = TaskDispatcher.createInstance()

        //3.添加任务并且启动任务
        dispatcher?.addTask(APPHelperTask(this))?.addTask(MMKVTask(this))?.addTask(AppManagerTask())
            ?.addTask(RefreshLayoutTask())

        AutoSize.initCompatMultiProcess(this)
        //屏幕适配监听器
        AutoSizeConfig.getInstance().setBaseOnWidth(false)
            .setLog(true).setOnAdaptListener(object : onAdaptListener {
                override fun onAdaptBefore(target: Any?, activity: Activity?) {
                    if (activity == null) {
                        return
                    }
                    //使用以下代码, 可以解决横竖屏切换时的屏幕适配问题
                    //首先设置最新的屏幕尺寸，ScreenUtils.getScreenSize(activity) 的参数一定要不要传 Application !!!
                    AutoSizeConfig.getInstance().screenWidth =
                        ScreenUtils.getScreenSize(activity)[0]
                    AutoSizeConfig.getInstance().screenHeight =
                        ScreenUtils.getScreenSize(activity)[1]
                    //根据屏幕方向，设置设计尺寸
                    if (activity.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        //设置横屏设计尺寸
                        AutoSizeConfig.getInstance()
                            .setDesignWidthInDp(1366)
                            .setDesignHeightInDp(768);
                    } else {
                        //设置竖屏设计尺寸
                        AutoSizeConfig.getInstance().setDesignWidthInDp(768)
                            .setDesignHeightInDp(1366)

                    }
                }

                override fun onAdaptAfter(target: Any?, activity: Activity?) {
                }
            })
        registerActivityLifecycle()
    }

    val viewModelStore by lazy { ViewModelStore() }

    /**
     * 获取启动器
     *
     * @return
     */
    fun getDispatcher(): TaskDispatcher? {
        return dispatcher
    }

    /**
     * 启动启动器
     *
     */
    fun startDispatcher() {
        dispatcher?.let {
            it.start()
            it.await()
        }
    }

    /**
     * 注册APP前后台切换监听
     */
    private fun appFrontBackRegister() {
        AppFrontBack.register(this, object : AppFrontBackListener {
            override fun onBack(activity: Activity?) {
                LogUtil.d("onBack")
            }

            override fun onFront(activity: Activity?) {
                LogUtil.d("onFront")
            }
        })
    }

    /**
     * 注册Activity生命周期监听
     */
    private fun registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                ActivityManager.push(activity)
                mCurrentActivity = activity
            }

            override fun onActivityStarted(activity: Activity) {
                mCurrentActivity = activity
            }

            override fun onActivityResumed(activity: Activity) {
                mCurrentActivity = activity
                AutoSize.autoConvertDensity(activity, 768F, false)
            }

            override fun onActivityPaused(activity: Activity) {
                mCurrentActivity = activity
            }

            override fun onActivityStopped(activity: Activity) {
                mCurrentActivity = activity
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                mCurrentActivity = activity
            }

            override fun onActivityDestroyed(activity: Activity) {
                ActivityManager.pop(activity)
                mCurrentActivity = null
            }
        })
        registerComponentCallbacks(object : ComponentCallbacks {
            override fun onConfigurationChanged(newConfig: Configuration) {
                if (mCurrentActivity == null) {
                    return
                }
                if (mAutoSizeRunnable != null) {
                    mHandler.removeCallbacks(mAutoSizeRunnable!!)
                }
                mAutoSizeRunnable = Runnable {
                    //获取当前屏幕的宽高
                    val screenSize = ScreenUtils.getScreenSize(mCurrentActivity);
                    //横屏
                    AutoSizeConfig.getInstance().screenWidth = screenSize[0]
                    AutoSizeConfig.getInstance().screenHeight = screenSize[1]

                    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        //设置横屏设计尺寸
                        AutoSizeConfig.getInstance()
                            .setDesignWidthInDp(1024)
                            .setDesignHeightInDp(600)
                    } else {
                        //设置竖屏设计尺寸
                        AutoSizeConfig.getInstance()
                            .setDesignWidthInDp(600)
                            .setDesignHeightInDp(1024)
                    }
                    //重新设置 dpi
                    if (mCurrentActivity != null) {
                        AutoSize.autoConvertDensityOfGlobal(mCurrentActivity)
                    }
                }
                mHandler.postDelayed(mAutoSizeRunnable!!, 500)
            }

            override fun onLowMemory() {

            }
        })
    }
}